package com.module.overview.ui.exerciseDetails

import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.Typeface
import android.os.Build
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.animation.AccelerateDecelerateInterpolator
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.common.app.base.AppActivity
import com.common.app.core.RouterHub
import com.common.app.data.bean.KeyBundle
import com.common.app.data.bean.KeyPre
import com.common.app.dialog.CommonShareDialog
import com.common.app.utls.Constants
import com.common.app.utls.TimeUtils
import com.common.app.utls.TimeUtils.calculateTimeBreakpointsRounded
import com.common.base.app.extras.addRoundCornersWithBorder
import com.common.base.app.extras.doOnIOThread
import com.common.base.app.extras.doOnUiThread
import com.common.base.app.extras.formatDecimal
import com.common.base.app.extras.getContext
import com.common.base.app.extras.loadCircle
import com.common.base.app.extras.loadId
import com.common.base.app.extras.setOnClickListener
import com.common.base.app.extras.setViIn
import com.common.base.app.extras.yes
import com.common.base.utils.BitmapUtils
import com.common.base.utils.BitmapUtils.shotScrollView
import com.common.base.utils.JsonUtils
import com.common.base.utils.MathUtil
import com.common.base.utils.SpUtilsManagement
import com.common.base.utils.SpanUtils
import com.common.base.utils.StatusBarUtils
import com.common.base.utils.UnitConversionUtils
import com.common.base.utils.ViewUtils
import com.module.ble.data.bean.CusChartData
import com.module.ble.repo.HeartRateRepo
import com.module.ble.repo.SportRecordRepo
import com.module.fitness.utils.getExTypeToName
import com.module.overview.R
import com.module.overview.databinding.OverviewActivityExerciseDetailsBinding
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.schedulers.Schedulers
import java.util.concurrent.TimeUnit


/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2025/06/25
 * <p>
 * 描述：运动详情页面
 * <p>
 * 修订历史：
 */
@Route(path = RouterHub.ROUTER_OVERVIEW_EXERCISE_DETAILS)
class ExerciseDetailsActivity :
    AppActivity<OverviewActivityExerciseDetailsBinding, ExerciseDetailsViewModel>(),
    View.OnClickListener, CommonShareDialog.OnCommonShareDialogSaveListener {

    val TAG: String = ExerciseDetailsActivity::class.java.simpleName

    override fun getViewModel() = ExerciseDetailsViewModel::class.java

    override fun getViewContentBinding() =
        OverviewActivityExerciseDetailsBinding.inflate(layoutInflater)

    override fun isShowToolBar(): Boolean = false
    override fun isStatusBarTranslate(): Boolean = true

    @Autowired(name = KeyBundle.BUNDLE_KEY)
    @JvmField
    var curSportId: Long = -1

    private var mBitmap: Bitmap? = null

    private val shareDialog by lazy { CommonShareDialog(this) }

    override fun initViews() {
        super.initViews()
        StatusBarUtils.setStatusBarHeight(mViewContentBinding.statusView)
        StatusBarUtils.setStatusBarForegroundColor(this, true)

        //上下拉刷新
        mViewContentBinding.pdView.setEnableLoadMore(false)
        mViewContentBinding.pdView.setEnableLoadMoreWhenContentNotFull(false)
        getRefreshFooter()?.let { mViewContentBinding.pdView.setRefreshFooter(it) }
        mViewContentBinding.pdView.setRefreshHeader(
            ClassicsHeader(this).setAccentColor(
                ContextCompat.getColor(this, R.color.color_999999)
            )
        )

    }

    override fun initEvents() {
        super.initEvents()

        mViewContentBinding.pdView.setRefreshFooter(
            ClassicsFooter(this).setAccentColor(
                ContextCompat.getColor(this, R.color.color_999999)
            )
        )

        mViewContentBinding.pdView.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                refreshLayout.layout.postDelayed({
                    finishPdView()
                }, 1000)
            }
        })

        shareDialog.setListener(this)

        mViewContentBinding.hrCurveChart.setTouchEnabled(false)
        mViewContentBinding.hrCurveChart.setXAxisSolidLineEnabled(true)

        mViewContentBinding.imgBack.setOnClickListener(onClick = this)
        mViewContentBinding.imgShare.setOnClickListener(onClick = this)
    }

    override fun lazyInitData() {
        super.lazyInitData()

        Constants.userBean?.let {
            mViewContentBinding.imgHead.loadCircle(it.avatar_url)
            mViewContentBinding.tvNikeName.text = if (it.getUserNickname().isNullOrEmpty()) it.mobile else it.getUserNickname()
        }

        getTheDaySportsData()

        with(mViewContentBinding.pBarWarmUp) {
            percent = 50f
            startAnimator(timeInterpolator = AccelerateDecelerateInterpolator(), duration = 1000)
        }

        with(mViewContentBinding.pBarFatBurning) {
            percent = 23f
            startAnimator(duration = 1000)
        }

        with(mViewContentBinding.pBarAerobicEndurance) {
            percent = 30f
//            startAnimator(timeInterpolator = BounceInterpolator(), duration = 1000)
            startAnimator(duration = 1000)
        }

        with(mViewContentBinding.pBarAnaerobicEndurance) {
            percent = 95f
            startAnimator(duration = 1000)
        }

        with(mViewContentBinding.pBarExtreme) {
            percent = 65f
            startAnimator(duration = 1000)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
    }

    override fun onClick(v: View?) {
        when (v) {
            mViewContentBinding.imgBack -> finish()
            mViewContentBinding.imgShare -> {
                setViIn(mViewContentBinding.imgBack, false)
                setViIn(mViewContentBinding.topRightMenuBg, false)
                setViIn(mViewContentBinding.imgShare, false)
                setViIn(mViewContentBinding.imgDelete, false)

                shotScrollView(mViewContentBinding.nswView)?.run {
                    setViIn(mViewContentBinding.imgBack, true)
                    setViIn(mViewContentBinding.topRightMenuBg, true)
                    setViIn(mViewContentBinding.imgShare, true)
                    setViIn(mViewContentBinding.imgDelete, true)

                    // 使用扩展函数处理圆角和边框
                    mBitmap = this.addRoundCornersWithBorder(
                        cornerRadius = 20f,
                        borderWidth = 15f,
                        borderColor = Color.WHITE
                    )
                    shareDialog.show()
                }
            }
        }
    }

    private fun finishPdView() {
        mViewContentBinding.pdView.finishRefresh()
        mViewContentBinding.pdView.finishLoadMore()
        mViewContentBinding.pdView.setNoMoreData(true)
    }

    @SuppressLint("CheckResult")
    private fun savePic() {
        showDialogLoading()
        // 延时半秒弹框完成
        Observable.timer(500, TimeUnit.MILLISECONDS)
            .subscribeOn(Schedulers.computation())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                if (mBitmap == null) {
                    dismissLoadingDialog()
                    return@subscribe
                }
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    BitmapUtils.saveImageToGallery4(getContext(), mBitmap)
                } else {
                    BitmapUtils.saveImageToGallery(getContext(), mBitmap)
                }
                dismissLoadingDialog()
            }
    }

    override fun onShareDialogSaveClick(mBmp: Bitmap?) {
//        RxPermissionHelper.request(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) {
//            if (it) {
        savePic()
//            } else {
//                ToastUtils.showToast("存储权限被拒绝！")
//            }
//        }
    }



    /**
     * 获取当天运动信息
     */
    fun getTheDaySportsData(){

        SportRecordRepo.instance.findAllById(curSportId)?.let { originalIt->
//            val listItStr = JsonUtils.toJson(originalIt)
            mViewContentBinding.tvExTime.text = "${TimeUtils.getMonthDay_(originalIt.startTs)}  ${TimeUtils.getHourMinute(originalIt.startTs)}-${TimeUtils.getHourMinute(originalIt.endTs)}"
            mViewContentBinding.tvExType.text = getExTypeToName(originalIt.sportType)

//            mViewContentBinding.tvExDuration.text = TimeUtils.formatTime(originalIt.duration*(1000), showHour = true, showMin = true)
            mViewContentBinding.tvExDuration.text = TimeUtils.formatTime3(originalIt.duration*(1000))

            mViewContentBinding.tvExCalorie.text = originalIt.calories.toInt().toString()

            var distanceValue = MathUtil.div(originalIt.distance.toString(), "100.00",false)
            (SpUtilsManagement.getInt(KeyPre.KEY_METERING_UNIT_LENGTH,0) !=0).yes {
                distanceValue = UnitConversionUtils.convertLength(originalIt.distance.toDouble(), UnitConversionUtils.LengthUnit.M, UnitConversionUtils.LengthUnit.MI).formatDecimal(2)
            }
            mViewContentBinding.tvDistance.text = distanceValue
            mViewContentBinding.tvExDistanceHint.text = "${getString(R.string.common_distance_hint)}(${if(SpUtilsManagement.getInt(KeyPre.KEY_METERING_UNIT_LENGTH,0) !=0) getString(R.string.common_mile_splice) else getString(R.string.common_kilometers_splice)})"

            getSleepTheDayHr(originalIt.startTs, originalIt.endTs)
        }
    }


    /**
     * 获取当天心率
     */
    private fun getSleepTheDayHr(startTime:Long, endTime:Long){
        if (startTime <=0 ||endTime <=0) return

        //睡眠心率
        HeartRateRepo.instance.findByTimeRange(startTime, endTime)?.let {listIt->
            if (listIt.isNullOrEmpty()) return

//            val listItStr = JsonUtils.toJson(listIt)
            // 创建48个时间区间块的CusChartData数组
            val sleepHrData = mutableListOf<CusChartData>()
            val timeDuration = endTime - startTime
            val intervalDuration = timeDuration / 48 // 每个时间区间的时长

            // 初始化48个时间区间块
            for (i in 0 until 48) {
                val intervalStartTime = startTime + (i * intervalDuration)
                val intervalEndTime = startTime + ((i + 1) * intervalDuration)
                sleepHrData.add(
                    CusChartData(
                        createdTime = intervalStartTime,
                        endTime = intervalEndTime,
                        minValue = 0f,
                        mValue = 0f,
                        dayNum = 0
                    )
                )
            }

//            val sleepHrDataInitStr = JsonUtils.toJson(sleepHrData)

            // 将listIt数组的数据根据createdTime分配到对应的时间区间块
            listIt.sortedBy { it.createdTime }.forEach { heartRateData ->
                // 计算该心率数据属于哪个时间区间块
                val timeOffset = heartRateData.createdTime - startTime
                val intervalIndex = (timeOffset / intervalDuration).toInt()

                // 确保索引在有效范围内
                if (intervalIndex in 0 until 48) {
                    val currentData = sleepHrData[intervalIndex]
                    // 将心率值累加到对应区间块的mValue中
                    if (currentData.mValue == 0f) {
                        // 如果是第一个数据，直接赋值
                        currentData.mValue = heartRateData.heartRate.toFloat()
                    } else {
                        // 如果已有数据，可以选择取平均值或最大值等策略
                        // 这里采用平均值策略
                        currentData.mValue = (currentData.mValue + heartRateData.heartRate.toFloat()) / 2f
                    }
                }
            }

            val minTemp = ((listIt.minOfOrNull { it.heartRate } ?: 30f).toFloat())
            val maxTemp = ((listIt.maxOfOrNull { it.heartRate } ?: 125f).toFloat())
            val theDayAverage = if (listIt.isNotEmpty()) {//当日平均
                listIt.map { it.heartRate }.average().toInt()
            } else {
                60f
            }

//            val sleepHrDataStr = JsonUtils.toJson(sleepHrData)

            val commonPoints = calculateTimeBreakpointsRounded(listIt.firstOrNull()?.createdTime?:0,listIt.lastOrNull()?.createdTime?:0) as MutableList<String>
            mViewContentBinding.hrCurveChart.setTimeLabels(commonPoints)

            mViewContentBinding.tvAverageHrv.text = theDayAverage.toInt().toString()
            mViewContentBinding.tvMaxHrv.text = maxTemp.toInt().toString()

            mViewContentBinding.hrCurveChart.setYRangeBackground(startValue = 55f,endValue = 65f,backgroundColor = ViewUtils.getColor(R.color.c_f7ebf2)
            )
            // 设置Y轴阶段
            mViewContentBinding.hrCurveChart.setYAxisStages(
                floatArrayOf(minTemp-10f, ((maxTemp-minTemp)/2).toInt()+minTemp, maxTemp+10f), // 阶段分界点
            )

            mViewContentBinding.hrCurveChart.setData(sleepHrData)

//            doOnUiThread {
//            }

        }
    }
}